﻿using MailDAL;
using MailTool.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MailTool.Pages
{
    public partial class SendMail : System.Web.UI.Page
    {
        UnitOfWork unitOfWork = new UnitOfWork();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!base.IsPostBack)
            {
                this.BindData();
            }
        }

        /// <summary>
        /// 绑定信息
        /// </summary>
        public void BindData()
        {
            //绑定收件人列表
            int size = this.Pagination.PageSize;
            int pageIndex = this.Pagination.PageIndex;
            pageIndex = pageIndex == 0 ? 0 : pageIndex - 1;
            int recordCount = unitOfWork.AddressListRepository.Get(p => p.OwnerId == SessionState.CurrentUser.Id).Count();

            List<MailModel.AddressList> list = unitOfWork.AddressListRepository.Get(p => p.OwnerId == SessionState.CurrentUser.Id, p => p.OrderBy(x => x.UserName), size, size * pageIndex, p => p.User).ToList();

            this.rptNewsList.DataSource = list;
            this.rptNewsList.DataBind();
            this.Pagination.BindName = "BindData";
            this.Pagination.Count = recordCount;
            this.Pagination.BindPager();

            //绑定模板列表
            List<MailModel.MailFromList> listMailFrom = unitOfWork.MailFromListRepository.Get(p => p.Id != 0).ToList();
            ddlSend.DataSource = listMailFrom;
            ddlSend.DataTextField = "MailTag";
            ddlSend.DataValueField = "Id";
            ddlSend.DataBind();

            //绑定模板列表
            List<MailModel.Template> listTemplate = unitOfWork.TemplateRepository.Get(p => p.Id != 0).ToList();
            ddlTemplate.DataSource = listTemplate;
            ddlTemplate.DataTextField = "TemplateName";
            ddlTemplate.DataValueField = "Id";
            ddlTemplate.DataBind();
        }

        /// <summary>
        /// 搜索收件人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSearchRecord_Click(object sender, EventArgs e)
        {
            string search = txtSearch.Text.Trim();

            int size = this.Pagination.PageSize;
            int pageIndex = this.Pagination.PageIndex;
            pageIndex = pageIndex == 0 ? 0 : pageIndex - 1;
            int recordCount = unitOfWork.AddressListRepository.Get(p => p.UserName.Contains(search) || p.Address.Contains(search) || p.Tag.Contains(search)).Count();

            var list = unitOfWork.AddressListRepository.Get(p => p.UserName.Contains(search) || p.Address.Contains(search) || p.Tag.Contains(search),
                    p => p.OrderBy(x => x.UserName),
                    size,
                    size * pageIndex,
                    p => p.User
                ).ToList();

            this.rptNewsList.DataSource = list;
            this.rptNewsList.DataBind();
            this.Pagination.BindName = "BindData";
            this.Pagination.Count = recordCount;
            this.Pagination.BindPager();
        }
        
        //发送邮件
        protected void btnSend_Click(object sender, EventArgs e)
        {
            bool result = true;
            try
            {
                foreach (RepeaterItem item in this.rptNewsList.Items)
                {
                    CheckBox CheckboxSign = item.FindControl("ChkSelect") as CheckBox;
                    if (CheckboxSign.Checked == true)
                    {
                        //先获取接收者邮件信息
                        int mailToId = Convert.ToInt32(((HiddenField)this.rptNewsList.Items[item.ItemIndex].FindControl("HiddenId")).Value);
                        MailModel.AddressList to = unitOfWork.AddressListRepository.Get(p => p.Id == mailToId).FirstOrDefault();

                        //获取模板内容
                        int templateId = Convert.ToInt32(ddlTemplate.SelectedValue);
                        MailModel.Template templateInfo = unitOfWork.TemplateRepository.Get(p => p.Id == templateId).FirstOrDefault();

                        //先获取发送者邮件信息
                        int sendId = Convert.ToInt32(ddlSend.SelectedValue);
                        MailModel.MailFromList from = unitOfWork.MailFromListRepository.Get(p => p.Id == sendId).FirstOrDefault();

                        //邮件所需配置信息
                        string mailTo = to.Address;
                        string mailSubject = txtTitle.Text.Trim();
                        string mailContent = Server.HtmlDecode(templateInfo.TemplateContent);
                        string server = from.MailServer;
                        string fromStr = from.MailFrom;
                        string password = from.MailPassword;

                        bool tempResult=MailUtil.SendEmail(mailTo, mailSubject, mailContent, server, fromStr, password);

                        result = result && tempResult;
                        MailModel.MailLogs log = new MailModel.MailLogs();
                        log.MailTitle = mailSubject;
                        log.SendUserId = SessionState.CurrentUser.Id;
                        log.ReceiverMailId = mailToId;
                        log.TemplateId = templateId;
                        log.SendStatus = tempResult;
                        log.SendDate = DateTime.Now;
                        log.MailFromId = from.Id;
                        unitOfWork.MailLogsRepository.Insert(log);
                        unitOfWork.Save(); 
                    }
                }
                if (result)
                    JsUtil.Alert("发送成功！", this.Page);
                else
                    JsUtil.Alert("发送失败或者部分发送失败！", this.Page);

            }
            catch
            {
                JsUtil.Alert("发送失败或者部分发送失败！", this.Page);
            }
        }
    }
}